<?php
/*************************
  Coppermine Photo Gallery
  ************************
  Copyright (c) 2003-2005 Coppermine Dev Team
  v1.1 originaly written by Gregory DEMAR

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.
  ********************************************
  Coppermine version: 1.4.8
  $Mod Revision: 2.5 $
  $Author: TranzNDance $
  $Date: 2006/06/25 $
  
  ************************
    Mod: Coppermine files mapped on Google Maps
	Demo: http://TakeThu.com Location Map
**********************************************/
if (!defined('IN_COPPERMINE')) { die('Not in Coppermine...');}

/* This is commented out for the time being. If IE acts up again, I will use this.
$browser = $_SERVER["HTTP_USER_AGENT"];

if(eregi("MSIE",$browser)) {
	$message = 'The developer of the Google Maps mod for Coppermine Photo Gallery got fed up spending extra time and effort so that cr@ppy IE can show the mashup. Please use another browser if you want to view the map of this gallery\'s photos. Firefox is recommended. If you can fix the issue <a href="http://groups.google.com/group/Google-Maps-API/browse_thread/thread/whatever">here</a>, please post a reply in that thread.';
	msg_box('IE must die', $message, $lang_continue, $ref);
} else {
*/

$map_key = $CONFIG['gmap_api_key'];
$use_dev_version = $CONFIG['gmap_version'];
// if version config is set not to use development version, use 2 (current stable), otherwise, use 2.x (latest development)
if ($use_dev_version == 1) {
	$version = '2.x';
} else {
	$version = '2';
}

$view = isset($_GET['view']) ? $_GET['view'] : 'no view';

$default_zoom_level = $CONFIG['gmap_default_zoom'];

if ($CONFIG['gmap_display_overview_map'] == 1) {
	$overview_map_size = $CONFIG['gmap_overview_map_size'];
	$overview_map_size_array = explode(',',$overview_map_size);
	$overview_map_width = $overview_map_size_array[0];
	$overview_map .= 'gmap.addControl(new GOverviewMapControl(new GSize(' . $overview_map_size . ')));'. "\n";	
} else {
	$overview_map = '';
}

$sum_latitude = array();
$sum_longitude = array();

$query=implode(' AND',$query);

if(count($FORBIDDEN_SET_DATA) > 0 ){
    $forbidden_set_string =" AND albums.aid NOT IN (".implode(",", $FORBIDDEN_SET_DATA).")";
} else {
    $forbidden_set_string = '';
}

//ordered by latitude so that the files are listed from north to south, in a way

if ($view == 'albums') {
	$view_param = '&view=albums';
	$order = "ORDER BY albums.latitude DESC,albums.longitude";
	$query = "SELECT avg(pictures.latitude) AS avg_latitude, avg(pictures.longitude) AS avg_longitude, albums.latitude AS album_latitude, albums.longitude AS album_longitude, pictures.*, albums.*, pictures.title AS pic_title, albums.thumb AS album_thumb, albums.description AS album_description
		FROM {$CONFIG['TABLE_PICTURES']} AS pictures, {$CONFIG['TABLE_ALBUMS']} AS albums
		WHERE pictures.aid = albums.aid
		AND ABS(pictures.latitude) + ABS(pictures.longitude) > 0
		$query $forbidden_set_string
		$query $album_set_string
		GROUP by pictures.aid
		$order;
		";

} else {
	if(is_numeric($album)) {
		$album_filter = "AND albums.aid = " . $album;
		$center_avg_coords = TRUE;
	} else {
		switch($album) {
			case 'lastcom': // Last comments
				$addFrom = ',' . "{$CONFIG['TABLE_COMMENTS']}";
				$album_filter = "AND {$CONFIG['TABLE_COMMENTS']}.pid = pictures.pid";
				break;
			case 'lastcomby': // Last comments by a specific user
				if (isset($_GET['uid'])) {
					$uid = (int)$_GET['uid'];
				} else {
						$uid = -1;
				}
				$addFrom = ',' . "{$CONFIG['TABLE_COMMENTS']}";
				$album_filter = "AND author_id = " . $uid ." AND {$CONFIG['TABLE_COMMENTS']}.pid = pictures.pid";
				break;
			case 'lastupby': // Last uploads by a specific user
					if (isset($_GET['uid'])) {
							$uid = (int)$_GET['uid'];
					} else {
							$uid = -1;
					}
				$addFrom = ',' . "{$CONFIG['TABLE_COMMENTS']}";
				$album_filter = "AND owner_id = " . $uid;
				break;
			case 'topn': // Most viewed pictures
				$album_filter = "AND hits > 0";
				break;
			case 'toprated': // Top rated pictures
				$album_filter = "AND pictures.votes >= '{$CONFIG['min_votes_for_rating']}'";
				break;
			case 'favpics': // Favourite Pictures.
				if (count($FAVPICS)>0){
					$favs = implode(",",$FAVPICS);
					$album_filter = "AND pictures.pid IN (" . $favs . ")";
				}
				break;
		}
	}
	$order = "ORDER BY pictures.latitude DESC,pictures.longitude";
	
	$query = "SELECT pictures.*, albums.*, pictures.title AS pic_title, pictures.latitude AS pic_latitude, pictures.longitude AS pic_longitude
				FROM {$CONFIG['TABLE_PICTURES']} AS pictures, {$CONFIG['TABLE_ALBUMS']} AS albums
				$addFrom
				WHERE approved = 'YES'
				AND pictures.aid = albums.aid 
				AND ABS(pictures.latitude) + ABS(pictures.longitude) > 0
				$album_filter
				$query $forbidden_set_string
				$query $album_set_string
				$order
				$limit
				;";
}
$result = cpg_db_query($query);

if (mysql_num_rows($result) > 0) {
	while($row = mysql_fetch_array($result)) {
		$album_thumb = $row['album_thumb'];
		$album_thumb_url = get_pic_url($album_thumb, 'thumb');
		$CURRENT_PIC_DATA = $row; //send a copy to get_pic_url it messes with the vars
		$thumb_link = $CONFIG['ecards_more_pic_target'].'displayimage.php?pos='.(-$row['pid']);
		$thumb_url = get_pic_url($CURRENT_PIC_DATA, 'thumb');
		$thumb_caption = strip_tags(bb_decode($row['caption'], $CONFIG['ecards_more_pic_target']));
		$thumb_caption = addslashes(str_replace(array("\r\n","\r","\n"), "<br />", $thumb_caption));
		if ($CONFIG['enable_smilies']) {
			$thumb_caption = process_smilies($thumb_caption);
			$album_caption = process_smilies(addslashes(str_replace(array("\r\n","\r","\n"), "<br />", strip_tags(bb_decode($row['album_description'], $CONFIG['ecards_more_pic_target'])))));
		} else {
			$thumb_caption = $thumb_caption;
			$album_caption = addslashes(str_replace(array("\r\n","\r","\n"), "<br />", strip_tags(bb_decode($row['album_description'], $CONFIG['ecards_more_pic_target']))));
		}
		$album_title = addslashes($row['title']);
		$album_link = $CONFIG['ecards_more_pic_target'].'thumbnails.php?album='.($row['aid']);
		$album_link_title = sprintf($lang_gmap_php['view_album'], $album_title);
		$owner_name = addslashes($row['owner_name']);
		$owner_link = $CONFIG['ecards_more_pic_target'].'profile.php?uid='.($row['owner_id']);
		$profile_link_title = sprintf($lang_gmap_php['view_profile'], $owner_name);
		$permalink_link_title = $lang_gmap_php['map_permalink'];
		$tab_max_char = $CONFIG['gmap_tab_max_char'];
		
		// title string: If there is no title, use the filename
		if (strlen($row['pic_title']) > 0) {
			$thumb_title = $row['pic_title'];
		} else {
			$thumb_title = $row['filename'];
		}
	
		if ($view == 'albums') {
			if (strlen($row['album_latitude']) == 0) {
				$latitude = $row['avg_latitude'];
				$longitude = $row['avg_longitude'];
			} else {
				$latitude = $row['album_latitude'];
				$longitude = $row['album_longitude'];
			
			}
			array_push ($sum_latitude,$latitude);
			array_push ($sum_longitude,$longitude);
			$details = addslashes($lang_picinfo['Album name']) . ': <a href="' . $album_link . '" title="' . $album_link_title . '">' . $album_title . "</a><br/><br/>" .  $album_caption;
			
			//truncate the tab title if it's too long
			if (strlen($album_title) > $tab_max_char) {
				$tab_title = substr($album_title, 0, $tab_max_char) . '...';
			} else {
				$tab_title = $album_title;
			}
			
		} else {
			$latitude = $row['pic_latitude'];
			$longitude = $row['pic_longitude'];
	
			array_push ($sum_latitude,$latitude);
			array_push ($sum_longitude,$longitude);
			
			//Infowindow content
			$details = "<a href=\"" . $thumb_link . '"><img src="' . $CONFIG['ecards_more_pic_target'].$thumb_url . '" class="image";></a><br/><b>' . $thumb_title . '</b><hr/>' . $thumb_caption . '<br/><br/>' . addslashes($lang_picinfo['Album name']) . ': <a href="' . $album_link . '" title="' . $album_link_title . '">' . $album_title . "</a></i><br/>" .
			$lang_adv_opts['owner_name'] . ': <a href="' . $owner_link . '" title="' . $profile_link_title . '">' . $owner_name . '</a>';
			
			//generate code for the points
			if (strlen($thumb_title) > $tab_max_char) {
				$tab_title = substr($thumb_title, 0, $tab_max_char) . '...';
			} else {
				$tab_title = $thumb_title;
			}
		}
		
		$point_code .= '
			AddTab(' . $latitude . ',' . $longitude . ',"' . $tab_title . '",'
				. "TabContent('<div class=\"tableb_compact infowindow\" >" . $details . '</div>\'),' . "'<img src=\"" . $CONFIG['ecards_more_pic_target'].$thumb_url . '" border="0";><br/>\'' . ', gmap);';
	} //end while

	$avg_latitude = array_sum($sum_latitude) / sizeof($sum_latitude);
	$avg_longitude = array_sum($sum_longitude) / sizeof($sum_longitude);
	
	// by default, the center coordinate is the average value of latitude and longitude
	if ($center_avg_coords) {
		$default_center_coords = $avg_latitude . ',' . $avg_longitude;
	} else { //it can be overridden with a manual entry in Config
		$def_coordinates = explode(',',$CONFIG['gmap_default_center']);
		$default_center_coords = $def_coordinates[0] . ',' . $def_coordinates[1];
	}
	
	$default_center_coord = isset($_GET['ll']) ? $_GET['ll'] : $default_center_coords;
	$zoom_level = isset($_GET['z']) ? $_GET['z'] : $default_zoom_level;
	
	if($album){
	 $album_param = '&album=' . $album;
	}

	if ($CONFIG['gmap_display_permalink'] == 1) {
		$permalink = <<<EOT
			'<a href="{$CONFIG['gmap_filename']}?ll=' + latLngStr + '&z=' + zoom + '{$album_param}{$view_param}">{$permalink_link_title}</a>&nbsp; | ' + latLngStr
EOT;
		$message = <<<EOT
		var zoom = gmap.getZoom();
		document.getElementById("message").innerHTML = ' | ' + $permalink;
EOT;
	} else {
		$message = <<<EOT
		document.getElementById("message").innerHTML = ' | ' + latLngStr;
EOT;
	}

mysql_close($link);

if ($CONFIG['gmap_display_coordinates'] == 1) {
	//This is where the "message" goes. In this case, the message will be the coordinates of a point that is double-clicked on the map   
	$coord_info = '<span id="message"></span>';
}

if ($PHP_SELF != 'thumbnails.php') {
	if ($view != 'albums') {
		$view_link = $lang_gmap_php['view_markers'] . ': ' . $lang_cat_list['pictures'] . ' | <a href="?view=albums">'. $lang_cat_list['albums'] . '</a>';
		$nav_info = $return . ' [' . $view_link . '] ' . $coord_info;
	} else {
		$view_link = $lang_gmap_php['view_markers'] . ': <a href="' . $PHP_SELF . '">'. $lang_cat_list['pictures'] . '</a> | ' . $lang_cat_list['albums'];
		$nav_info = '[' . $view_link . '] ' . $coord_info;
	}
}

if ($show_sidebar) {
	starttable('100%', $title,2); //two columns if there is a sidebar
echo <<<EOT
	<tr><td colspan="2">$nav_info</td></tr>
EOT;
} else {
	starttable('100%', $title);
echo <<<EOT
	<tr><td align="center">$nav_info</td></tr>
EOT;
}

if ($CONFIG['gmap_display_geocode_addressbar'] == 1) {
?>
	<tr>
<?php
	if ($show_sidebar) {
		echo '<td valign="top" align="center" colspan="2">';
	} else {
		echo '<td valign="top" align="center">';
	}
echo <<<EOT
			<form action="#" onsubmit="ShowAddress(this.address.value); return false">
				<input type="text" size="60" name="address" value="{$CONFIG['gmap_geocode_default_address']}"  class="textinput" />
				<input type="submit" value="{$lang_main_menu['search_lnk']}" class="button" />
			</form>
		</td>
	</tr>
EOT;
}
?>
	<tr>
		<td valign="top" align="center">
			<noscript>
			<?php echo $lang_gmap_php['no_javascript'] ?>
			</noscript>
			
			<!-- This is where the map goes -->    
			<div id="gmap"></div>
		</td>
<?php
if ($show_sidebar) {
	//Based on Config setting, this displays a list of available items
echo <<<EOT
	<td valign="top" width="{$CONFIG['gmap_sidebar_width']}">
	<div id="gmap_sidebar" class="thumbnails"></div>
	</td>
EOT;
}
echo '</tr>';
endtable();

$gmap_code =  <<<EOT
<script src="http://maps.google.com/maps?file=api&amp;v=$version&amp;key=$map_key" type="text/javascript">
</script>
<script type="text/javascript">
//<![CDATA[

// Create global variables, this makes things simpler.
lastmarker = null;
geocoder = null;
geocodedPoint = null;
geocodeInfowindow = null;
savedAddress = null;
point = null;

function ShowContent() {
}

function TabContent(details) {
	return (details);
}

function AddMarker(point, icon, tabs, gmap) {
	var newmarker = new GMarker(point, icon);
	newmarker.tabs = tabs;
	
	GEvent.addListener(newmarker, "click", function () {
		if (this.tabs.length > 4) {
			//gmap.setCenter(this.getPoint(), gmap.getZoom() + 2);
			gmap.zoomIn(this.getPoint(), true);
			gmap.zoomIn(this.getPoint(), true);
		} else {
			if (this.tabs.length > 2) {
				this.tabs[0].contentElem = '<div style="width:'+this.tabs.length*100+'px">' + this.tabs[0].contentElem + '</div>';
			} 
			var opts = new Object;
			this.openInfoWindowTabsHtml(this.tabs, opts);
		}
	});

	gmap.addOverlay(newmarker);
	return newmarker;
}

function AddTab(lat, lng, label, content, name, gmap) {
	var bounds = gmap.getBounds();
	var cluster_tolerance = 15; //smaller value = more clustering, more marker per cluster, further apart; 
								//bigger value = more individual markers, closer together
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var latRange = northEast.lat()-southWest.lat();
	var lngRange = northEast.lng()-southWest.lng();
	while (latRange < 0.0) latRange += 360.0;
	while (lngRange < 0.0) lngRange += 360.0;
	var latDelta = (latRange / cluster_tolerance);
	var lngDelta = (lngRange / cluster_tolerance);
	
	if (lastmarker != null &&
		lastmarker.getPoint().lat() - lat < latDelta &&
		lastmarker.getPoint().lng() - lng < lngDelta) {
		// Add a tab to the last marker since this new point is for the same location
		lastmarker.tabs.push(new GInfoWindowTab(label, content));
		
		if (lastmarker.tabs.length > 4) {
			gmap.removeOverlay(lastmarker);
			lastmarker = AddMarker(lastmarker.getPoint(), clusterIcon, lastmarker.tabs, gmap);
		}
	} else {
		lastmarker = AddMarker(new GLatLng(lat, lng), baseIcon, [new GInfoWindowTab(label, content)], gmap);
	}
  
	var sidebar = document.getElementById("gmap_sidebar");
	if (sidebar != null) {
		var tabblocks = sidebar.getElementsByTagName("div");
		var curblock = null;
		if (tabblocks.length == 0 || lastmarker.tabs.length == 1) {
			var separator = document.createElement("hr");
			sidebar.appendChild(separator);	
			curblock = document.createElement("div");
			curblock.setAttribute("class", "sidebar_group");
			sidebar.appendChild(curblock);	
		} else {
			curblock = tabblocks[tabblocks.length - 1];
		}
		var thumb = document.createElement("a");
		thumb.setAttribute("href", "javascript:ShowContent()");
		thumb.innerHTML = name;
		thumb.marker = lastmarker;
		thumb.tabs = [];
		thumb.tab = lastmarker.tabs.length - 1;
		
		GEvent.addDomListener(thumb, "click", function () {
			this.marker.openInfoWindowHtml(this.marker.tabs[this.tab].contentElem);
		});
		
		curblock.appendChild(thumb);
	}
}

//add the points
function AddAllTabs() {
	{$point_code}
}

//add geocoding functionality
function DisplayAddress(point, geocodeInfowindow) {
	var marker = new GMarker(point,geocodeIcon);
	gmap.addOverlay(marker);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(geocodeInfowindow);
		//marker.showMapBlowup();
	});
	return(marker);
}

function ShowAddress(address) {
	geocoder.getLatLng(address,
		function(point) {
			if (!point) {
				alert(address + " not found");
			} else {
				//store the address as global var so it can be used later
				savedAddress = address;
				gmap.setCenter(point, gmap.getZoom());
				geocodedPoint = point;
				geocodeInfowindow = '<div class="tableb_compact infowindowAddress">' + 
				'<img src="' + "{$CONFIG['ecards_more_pic_target']}markers/numbered_marker.php?image=pushpins/webhues/011.png&text=X" + '" />'
				 + savedAddress + '<br/>' + point + '</div>';
				var marker = DisplayAddress(point, geocodeInfowindow);
				//show infowindow for search result
				marker.openInfoWindowHtml(geocodeInfowindow);
				return (address);
			}
		}
	);
}

if (GBrowserIsCompatible()) {
    // Create a base icon for all of our markers that specifies the shadow, icon dimensions, etc.
    var baseIcon = new GIcon();
	baseIcon.image = "{$CONFIG['ecards_more_pic_target']}markers/numbered_marker.php?image=pushpins/webhues/009.png";
    baseIcon.shadow = "http://www.google.com/intl/en_us/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GLatLng(34,9);
    baseIcon.infoWindowAnchor = new GLatLng(9, 2);
    baseIcon.infoShadowAnchor = new GLatLng(18, 25);
	baseIcon.imageMap = G_DEFAULT_ICON.imageMap;
	baseIcon.transparent = G_DEFAULT_ICON.transparent;
	
    // Create a cluster icon for clustered markers
	var clusterIcon = new GIcon(baseIcon);
	clusterIcon.image = "{$CONFIG['ecards_more_pic_target']}markers/numbered_marker.php?image=pushpins/webhues/088.png&text=more&scale=1.5";
	clusterIcon.iconSize = new GSize(30,51);
	clusterIcon.shadowSize = new GSize(56,51);
	clusterIcon.imageMap = G_DEFAULT_ICON.imageMap;
	clusterIcon.transparent = G_DEFAULT_ICON.transparent;
	
    // Create a geocode icon for geocoded marker
	var geocodeIcon = new GIcon(baseIcon);
	geocodeIcon.image = "{$CONFIG['ecards_more_pic_target']}markers/numbered_marker.php?image=pushpins/webhues/011.png&text=X";

    //create the map, this is stored in a global variable for easy access
    var gmap = new GMap2(document.getElementById("gmap"));
	gmap.setCenter(new GLatLng({$default_center_coord}), {$zoom_level}, {$CONFIG['gmap_type']});
    gmap.addControl(new GLargeMapControl());
    gmap.addControl(new GMapTypeControl());
	gmap.addControl(new GScaleControl()); 
	{$overview_map}
	geocoder = new GClientGeocoder();
	gmap.enableContinuousZoom();
	//gmap.enableDoubleClickZoom();
	
	AddAllTabs();
	
	//gets the coordinate values and displays
	GEvent.addListener(gmap, "moveend", function() {
		var center = gmap.getCenter();
		var latLngStr = center.y + ',' + center.x;
		{$message}
	});

	//refreshes the map and sidebar when zooming and adds tabs according to new bounds info
	GEvent.addListener(gmap, "zoomend", function() {
		document.getElementById("gmap_sidebar").innerHTML = "";
		gmap.clearOverlays();
		AddAllTabs();
		if(geocodedPoint != null) {
			DisplayAddress(geocodedPoint, geocodeInfowindow);
		}
	});
} else {
	alert("Sorry, the Google Maps API is not compatible with this browser");
}
//]]>
</script>
EOT;
}//end if
?>